#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2025/1/31 22:09
# @Author  : Ramsey
# @Site    : zh
# @File    : settings_manager.py
# @Software: PyCharm
from copy import deepcopy
from importlib import import_module
from spider_framework.settings import default_settings


class SettingsManager:
    def __init__(self):
        self.attributes: dict = {}
        self.set_settings(default_settings)

    def __str__(self):
        return f"{self.attributes}"

    def __setitem__(self, key, value):
        self.set_item(key, value)

    def set_item(self, key, value):
        self.attributes[key] = value

    def __getitem__(self, item):
        if item not in self.attributes:
            return None
        else:
            return self.attributes[item]

    def get(self, name, default=None):
        return self[name] if name is not None else default

    def get_bool(self, name, default=False):
        got = self.get(name, default)
        try:
            return bool(int(got))
        except:
            if got.upper == "TRUE":
                return True
            if got.upper() == "FALSE":
                return False
            raise ValueError("Invalid bool value")

    def update_settings(self, values):
        if isinstance(values, dict):
            for k, v in values.items():
                self.set_item(k, v)

    def __delitem__(self, key):
        self.delete_item(key=key)

    def delete_item(self, key):
        del self.attributes[key]

    def set_settings(self, module):
        if isinstance(module, str):
            module = import_module(module)

        for key in dir(module):
            if key.isupper():
                self.set_item(key, getattr(module, key))

    def copy(self):
        return deepcopy(self)


if __name__ == "__main__":
    settings = SettingsManager()
    settings["concurrency"] = 16
    print(settings.attributes)
